package server.core;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import entity.Reply;

public class ConnectionListener {
	public static final int MAX_CONNECTION_NUMBER = 10;
	
	private ExecutorService pool = Executors.newFixedThreadPool(MAX_CONNECTION_NUMBER);
	volatile int freethreadCount = MAX_CONNECTION_NUMBER;

	public void listen() throws IOException {
		ServerSocket ss = new ServerSocket(49898);
		while (true) {
			Socket cs = ss.accept();
			// System.out.println("aaa");
			if (freethreadCount > 0) {
				freethreadCount--;
				pool.submit(new RequestHandler(cs, this));
			} else {
				ObjectOutputStream oos = new ObjectOutputStream(
						cs.getOutputStream());
				Reply rep = new Reply(-1);
				oos.writeObject(rep);
				cs.close();
			}
		}
	}
}
